package com.mazaiting.jetpack.architecture.paging.room

import android.arch.paging.PagedListAdapter
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import com.mazaiting.jetpack.R
import com.mazaiting.jetpack.architecture.paging.StudentRoom

/**
 * Student适配器
 * Created by mazaiting on 2018/7/26.
 */
class StudentAdapter : PagedListAdapter<StudentRoom, StudentAdapter.StudentViewHolder>(DIFF_CALLBACK) {
  override fun onBindViewHolder(holder: StudentViewHolder, position: Int) =
          holder.bindTo(getItem(position))
  
  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder =
          StudentViewHolder(parent)
    
  companion object {
    // Item回调
    private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<StudentRoom>() {
      // 条目是否相同
      override fun areItemsTheSame(oldItem: StudentRoom, newItem: StudentRoom): Boolean = oldItem.id == newItem.id
      // 内容是否相同
      override fun areContentsTheSame(oldItem: StudentRoom, newItem: StudentRoom): Boolean = oldItem == newItem
    }
  }
  
  class StudentViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
          // 加载布局
          LayoutInflater.from(parent.context).inflate(R.layout.item_student, parent, false)
  ) {
    // 查找view
    private val nameView = itemView.findViewById<TextView>(R.id.tv_name)
    // 创建数据
    private var student: StudentRoom? = null
  
    /**
     * 绑定数据
     */
    fun bindTo(student: StudentRoom?) {
      this.student = student
      // 设置文本
      nameView.text = student?.name
    }
  }
}